package com.lkx.farmershop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.mapper.UpvoteMapper;
import com.lkx.farmershop.model.entity.Tuan;
import com.lkx.farmershop.model.entity.Upvote;
import com.lkx.farmershop.service.TuanService;
import com.lkx.farmershop.service.UpvoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * (Upvote)表服务实现类
 *
 * @author makejava
 * @since 2025-02-24 00:08:10
 */
@Service("upvoteService")
public class UpvoteServiceImpl extends ServiceImpl<UpvoteMapper, Upvote> implements UpvoteService {

    @Autowired
    private TuanService tuanService;

    @Override
    public ApiResult<String> upvote(Long userId, Long tuanId) {
        //查询是否已经点赞
        Upvote upvote = lambdaQuery().eq(Upvote::getUserId, userId)
                .eq(Upvote::getTuanId, tuanId).one();
        if (upvote != null) {
            //如果已经点赞，则删除
            removeById(upvote.getId());
            //更新点赞量
            Tuan tuan = tuanService.lambdaQuery().eq(Tuan::getTuanId, tuanId).one();
            tuan.setUpvoteCount(tuan.getUpvoteCount() - 1);
            tuanService.updateById(tuan);
            return ApiResult.success("已取消点赞");
        } else {
            //如果没有点赞，则添加
            save(new Upvote(userId, tuanId));
            //更新点赞量
            Tuan tuan = tuanService.lambdaQuery().eq(Tuan::getTuanId, tuanId).one();
            tuan.setUpvoteCount(tuan.getUpvoteCount() + 1);
            tuanService.updateById(tuan);
            return ApiResult.success("点赞成功");
        }
    }

    @Override
    public ApiResult<Boolean> hasUpvote(Long tuanId, Long userId) {
        //判断是否已经点赞
        Upvote upvote = lambdaQuery().eq(Upvote::getUserId, userId)
                .eq(Upvote::getTuanId, tuanId).one();
        return ApiResult.success(upvote != null);
    }
}

